﻿using System;
using System.IO;
using System.Net;
using System.Text;
using FTchina.DAL;
using FTchina.Library;

namespace FTchina.OA
{
    /// <summary>
    ///UnicomSMS 的摘要说明
    /// </summary>
    public class UnicomSMS
    {

        private static string SURL = "http://10.72.32.119:9081/sms/Js_SMSSender.do?method=saveSMS";
        public UnicomSMS()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 通过接口发送短信
        /// </summary>
        /// <param name="targets">目标号码</param>
        /// <param name="from">来自</param>
        /// <param name="content">内容</param>
        /// <param name="systype">系统名称</param>
        /// <param name="ErrorMsg">错误日志</param>
        /// <returns></returns>



        public static Boolean SendSMS(string targets, string from, string content, out string ErrorMsg)
        {
            bool flag = true;
            string _ErrorMsg = string.Empty;
            ErrorMsg = string.Empty;

            if (targets.Contains(";"))
            {
                string[] targetss = targets.Split(';');

                foreach (string tar in targetss)
                {
                    if (tar != "")
                    {
                        flag = SendSingle(tar, from, content, out _ErrorMsg);
                        ErrorMsg += _ErrorMsg;
                    }
                }

            }

            else
            {
                flag = SendSingle(targets, from, content, out ErrorMsg);
            }


            return flag;
        }

        public static Boolean SendSingle(string target, string from, string content, out string ErrorMsg)
        {
            bool flag = true;
            ErrorMsg = string.Empty;

            target = target.Replace("+86", "").Replace(" ", "").Replace("-", "").Trim();

            if (target.Length != 11)
            {
                ErrorMsg += target + "手机号错误" + "<br>";
                flag = false;
            }
            if (!(target.StartsWith("130") | target.StartsWith("131") | target.StartsWith("132") | target.StartsWith("145") | target.StartsWith("155") | target.StartsWith("156") | target.StartsWith("186")))
            {

                ErrorMsg += target + "只支持联通号码" + "<br>";
                flag = false;
            }

            if (content.Length == 0)
            {
                ErrorMsg += target + "内容不能为空" + "<br>";
                flag = false;
            }


            if (flag)
            {

                string url = SURL;
                string body = content;

                content = from + ":" + content;

                string poststr = "userMobile=" + from + "&userId=null&smsFlag=0&logType=%B6%CC%D0%C5%B7%A2%CB%CD&logCo=10.72.34.135&optType=%B6%CC%D0%C5%B7%A2%CB%CD&toPhoneNumber=" + target + "&content=" + body + "&sengflag=yes";



                //if (!CloudSend(target,content))
                //{
                //    flag = false;
                //    ErrorMsg += target + "发送失败";

                //}

                if (!Post2Http(url, Encoding.GetEncoding("gb2312"), poststr).Contains("发送成功。"))
                {
                    flag = false;
                    ErrorMsg += target + "发送失败";

                }
                else
                {
                    ErrorMsg += target + "发送成功";

                    Save2DB(target + ":" + body);//保存到数据库
                }
            }
            ErrorMsg += "   " + DateTime.Now.ToString() + "<br>";
            return flag;
        }





        ///Post2Http(url, Encoding.GetEncoding("gb2312"), poststr2
        /// <summary>
        /// 向指定网址发送字符串
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="en">字符编码</param>
        /// <param name="poststr">发送字符串</param>
        /// <returns></returns>
        private static string Post2Http(string url, Encoding en, string poststr)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.CookieContainer = new CookieContainer();
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "post";
                byte[] bytes = en.GetBytes(poststr);
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), en);
                string str = reader.ReadToEnd();
                reader.Close();
                return str;
            }
            catch
            {
                return "";
            }
        }



        /// <summary>
        /// 保存到数据库备案
        /// </summary>
        /// <param name="content"></param>
        private static void Save2DB(string content)
        {
            FTchina.Models.Sms_Log mSms_Log = new FTchina.Models.Sms_Log();
            mSms_Log.Id = 0;
            mSms_Log.Sms = content;
            mSms_Log.Ip = RequestHelper.GetUserIp();
            mSms_Log.Dt = DateTime.Now;
            mSms_Log.UName = MasterHelper.UName;
            FTchina.BLL.Sms_LogManager.AddOrUpdateSms_Log(mSms_Log);
        }



        #region 云门户的短信发送

        /// <summary>
        /// 云门户的短信接口
        /// </summary>
        /// <param name="Num"></param>
        /// <param name="Content"></param>
        /// <returns></returns>
        protected static Boolean CloudSend(string Num,string Content)
        {
            //string Num = "15605468613";
            //string Content = "test";
            string date = DateTime.Now.Date.ToString();
            string url = "http://www.portal.unicom.local/unisappgerenduanxin/0/default/gsmsuser/add/?action=send";
            string post = "selectusers=-1%7C{0}%7C{0}&content={1}&istimingmsg=0&sendtime={2}+09%3A02";
            string rs = cloudPost2Https(url, Encoding.UTF8, string.Format(post, Num, Content,date));
            return (rs.Split(',')[0].Split(':')[1] != "0");
        }
        /// <summary>
        /// 云门户短信发送
        /// </summary>
        /// <param name="url"></param>
        /// <param name="en"></param>
        /// <param name="poststr"></param>
        /// <returns></returns>
        protected static string cloudPost2Https(string url, Encoding en, string poststr)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.CookieContainer = new CookieContainer();
                request.Timeout = 2000000000;
                request.KeepAlive = true;

                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "post";
                request.Accept = "application/json, text/javascript, */*; q=0.01";
                request.Referer = "http://www.portal.unicom.local/unisappgerenduanxin/0/default/gsmsuser/add/?action=writesms";
                request.Host = "www.portal.unicom.local";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)";
                request.Headers.Set("Accept-Language", "zh-cn");
                request.Headers.Set("x-requested-with", "XMLHttpRequest");
                request.Headers.Set("UA-CPU", "x86");
                request.Headers.Set("Accept-Encoding", "gzip, deflate");
                request.Headers.Set("Cookie", "winWidth=1260; winHeight=630; winWidth=1260; winHeight=630; sid=0d1q7ta2vn8fa5v18oee8r7kq6; PHPSESSID=6o30pcqb927cu9cunc6em19e41; setok=aTotMTs%3D; authcookie=czowOiIiOw%3D%3D; LtpaToken=tQX78YHEEn1YBvIwIQdNNzNwQ8Sv9jiP0kaYU9FlO4enYp3sT9h7jsOY4PK4XPttaziNuEtDH/iS0vr9OjBDRbLiKR4KHgKmTNRiOfrFFm5jk/piHvpDM5ODP7mjzJUx6a9WPQ3p40xeBapukwOuSW5TteKUAy4GLqzipEqQ3o48W6F0molneMcFx/Ax6+Y8DsEMCd+c20EJnppnLyFShaTrC7M3+AzerlaJoUHJxQamKJoL+LEEWeRCu9J0CkPxqt4rEbn7/gGzNVgwZ/eFbsELtUfCjcPonuo2R2n4H7s=");

                byte[] bytes = en.GetBytes(poststr);
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), en);
                string str = reader.ReadToEnd();
                reader.Close();
                return str;
            }
            catch
            {

                return "";
            }
        }
        #endregion
    }
}